package com.zaoshui.hudada.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zaoshui.hudada.common.ErrorCode;
import com.zaoshui.hudada.constant.CommonConstant;
import com.zaoshui.hudada.exception.BusinessException;
import com.zaoshui.hudada.exception.ThrowUtils;
import com.zaoshui.hudada.model.dto.useranswer.UserAnswerQueryRequest;
import com.zaoshui.hudada.model.entity.App;
import com.zaoshui.hudada.model.entity.UserAnswer;
import com.zaoshui.hudada.model.entity.User;
import com.zaoshui.hudada.model.enums.AppScoringStrategyEnum;
import com.zaoshui.hudada.model.enums.AppTypeEnum;
import com.zaoshui.hudada.model.vo.UserAnswerVO;
import com.zaoshui.hudada.model.vo.UserVO;
import com.zaoshui.hudada.service.AppService;
import com.zaoshui.hudada.service.UserAnswerService;
import com.zaoshui.hudada.mapper.UserAnswerMapper;
import com.zaoshui.hudada.service.UserService;
import com.zaoshui.hudada.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author lihai
* @description 针对表【user_answer(用户答题记录)】的数据库操作Service实现
* @createDate 2024-05-24 16:57:01
*/
@Service
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer>
    implements UserAnswerService{
    @Resource
    private UserService userService;

    @Resource
    private AppService appService;


    /*
     * 校验参数
     * */
    @Override
    public void validUserAnswer(UserAnswer userAnswer, boolean add) {
        if (userAnswer == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer appType = userAnswer.getAppType();
        Integer scoringStrategy = userAnswer.getScoringStrategy();
        String resultName = userAnswer.getResultName();
        String resultDesc = userAnswer.getResultDesc();
        Long appId = userAnswer.getAppId();
        Long id = userAnswer.getId();
        if(add){
            if(id == null || id <= 0){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不能为空");
            }
        }

        // 有参数则校验
        if (StringUtils.isNotBlank(resultName) && resultName.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结果名称过长");
        }
        if (StringUtils.isNotBlank(resultDesc) && resultDesc.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结果描述过长");
        }
        App app = appService.getById(appId);
        ThrowUtils.throwIf(app == null, ErrorCode.PARAMS_ERROR, "应用不存在");
    }

    /**
     * 获取查询包装类
     *
     * @param userAnswerQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<UserAnswer> getQueryWrapper(UserAnswerQueryRequest userAnswerQueryRequest) {
        QueryWrapper<UserAnswer> queryWrapper = new QueryWrapper<>();
        if (userAnswerQueryRequest == null) {
            return queryWrapper;
        }
        Long id = userAnswerQueryRequest.getId();
        Long appId = userAnswerQueryRequest.getAppId();
        Integer appType = userAnswerQueryRequest.getAppType();
        Integer scoringStrategy = userAnswerQueryRequest.getScoringStrategy();
        Long resultId = userAnswerQueryRequest.getResultId();
        String resultName = userAnswerQueryRequest.getResultName();
        String resultDesc = userAnswerQueryRequest.getResultDesc();
        Integer resultScore = userAnswerQueryRequest.getResultScore();
        Long userId = userAnswerQueryRequest.getUserId();
        String sortField = userAnswerQueryRequest.getSortField();
        String sortOrder = userAnswerQueryRequest.getSortOrder();

        //模糊查询
        queryWrapper.like(StringUtils.isNotBlank(resultName), "resultName", resultName);
        queryWrapper.like(StringUtils.isNotBlank(resultDesc), "resultDesc", resultDesc);

        //精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appId), "appId", appId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appType), "appType", appType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(scoringStrategy), "scoringStrategy", scoringStrategy);
        queryWrapper.eq(ObjectUtils.isNotEmpty(resultId), "resultId", resultId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(resultScore), "resultScore", resultScore);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public UserAnswerVO getUserAnswerVO(UserAnswer userAnswer, HttpServletRequest request) {
        UserAnswerVO userAnswerVO = UserAnswerVO.objToVo(userAnswer);
        long userAnswerId = userAnswer.getId();
        // 1. 关联查询用户信息
        Long userId = userAnswer.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        userAnswerVO.setUser(userVO);
        return userAnswerVO;
    }

    @Override
    public Page<UserAnswerVO> getUserAnswerVOPage(Page<UserAnswer> userAnswerPage, HttpServletRequest request) {
        List<UserAnswer> userAnswerList = userAnswerPage.getRecords();
        Page<UserAnswerVO> userAnswerVOPage = new Page<>(userAnswerPage.getCurrent(), userAnswerPage.getSize(), userAnswerPage.getTotal());
        if (CollUtil.isEmpty(userAnswerList)) {
            return userAnswerVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = userAnswerList.stream().map(UserAnswer::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<UserAnswerVO> userAnswerVOList = userAnswerList.stream().map(userAnswer -> {
            UserAnswerVO userAnswerVO = UserAnswerVO.objToVo(userAnswer);
            Long userId = userAnswer.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            userAnswerVO.setUser(userService.getUserVO(user));

            return userAnswerVO;
        }).collect(Collectors.toList());
        userAnswerVOPage.setRecords(userAnswerVOList);
        return userAnswerVOPage;
    }
}




